<template>
  <div class="plant">
    <header>
      <BaseNavBar title="添加植物" :is-nav="true" />
    </header>
    <main style="margin-top: 8px;">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field label="图片">
            <template #input>
              <SingleUploader @upload-success="(value) => {
                plant.cover = `/api/${value}`;
              }" />
            </template>
          </van-field>
          <van-field v-model="plant.nickname" name="nickname" label="昵称" placeholder="请输入植物昵称" />
          <van-field v-model="plant.variety" name="variety" label="品种" placeholder="品种" />
          <van-field v-model="plant.address" name="address" label="地址" placeholder="请输入地址" />
          <van-field v-model="plant.plantDate" name="plantDate" label="种植日期" placeholder="请选择种植日期"
            @click="show = true" />
        </van-cell-group>

        <div style="margin: 16px;">
          <van-button round block type="primary" color="#09BB07" native-type="submit">
            确定
          </van-button>
          <van-button style="margin-top: 8px;" round block type="primary" plain color="#09BB07" @click="handleReset">
            重置
          </van-button>
        </div>
      </van-form>
      <van-popup v-model:show="show" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
        <van-date-picker :min-date="new Date(1970, 0, 1)" title="请选择生日" @confirm="handleConfirm" @cancel="show = false" />
      </van-popup>
    </main>

  </div>
</template>

<script setup>
import { ref} from 'vue';
import { showToast} from 'vant';
import SingleUploader from '@/components/SingleUploader/index.vue';
import BaseNavBar from '@/components/BaseNavBar/index.vue';
import {addPlant} from '@/apis/plant';


const plant = ref({
  nickname: "",
  variety: "",
  plantDate: "",
  address: "",
  cover: "",
});
const show = ref(false);
const handleConfirm = ({ selectedValues = [] }) => {
  plant.value.plantDate = selectedValues?.join('-');
  show.value = false;
};
const onSubmit = async (values) => {

  try {
        const { code, msg } = await addPlant ({...values,cover:plant.value.cover});
        if (code === 200) {
          showToast('添加成功');
          return
        }
        showToast(msg);

      } catch (error) {
        console.log(error, 'error');

      }
};
const handleReset = () => {
  plant.value = {};
};
</script>

<style lang="less" scoped>
</style>
